package shiqi.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import shiqi.excelListener.DemoListener;
import shiqi.model.Demo;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author geo_tsg
 * @version 1.0.0
 * @ClassName EasyExcelController.java
 * @Description
 * @createTime 2022-04-20
 */
@RestController
@RequestMapping("/excel")
public class EasyExcelController {


    @GetMapping(path = "/download")
    public void download(HttpServletResponse response) throws IOException {
        try {
            String fileName = URLEncoder.encode("表名-" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()), "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            ExcelWriter excelWriter = EasyExcelFactory.write(response.getOutputStream()).build();
            List<Demo> list = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                Demo demo = new Demo();
                demo.setName1("name1-" + i);
                demo.setName2("name2-" + i);
                list.add(demo);
            }
            excelWriter.write(list, EasyExcelFactory.writerSheet(0, "name1").head(Demo.class).build());
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @GetMapping(path = "/upload")
    public boolean excel2Database(MultipartFile file) {
        try {
            EasyExcelFactory.read(file.getInputStream()).registerReadListener(new DemoListener()).head(Demo.class).sheet(0).doReadSync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }


}
